package controllers

import (
	"findme-api/models"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"strings"
)

type FenceController struct {
	beego.Controller
}

type Fence struct {
	Id string `json:"id"`
	Fenceid string `json:"fenceid"`
	Fencename string `json:"fencename"`
	Company string `json:"company"`
	Department string `json:"department"`
}




type FJSONS struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	Alldepartment []Department `json:"alldepartment"`
	Allarea []Area `json:"allarea"`
	DATA []Fence  `json:"data"`
}

//func (c *FenceController) fenceAllowCross() {
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS")    //允许post访问
//	//c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "GET")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
//	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
//}


//添加电子围栏
func (c *FenceController) Addfence() {
	FileLogs.Info("添加电子围栏")
	//c.fenceAllowCross()
	fenceid:= c.GetString("fenceid")
	fencename:= c.GetString("fencename")
	fencepoint := c.GetString("fencepoint")
	FileLogs.Info("fenceid:",fenceid)
	FileLogs.Info("fencename:",fencename)
	FileLogs.Info("fencepoint:",fencepoint)
	token := c.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)

	fence := models.FenceInfo{Fenceid:fenceid,Fencename:fencename,Fencepoint:fencepoint,Company:company,Department:"未添加"}
	id,_:= models.AddFence(&fence)
	FileLogs.Info("id: ",id)
	c.Ctx.WriteString("add fence successfully")
}


//加载所有电子围栏
func (c *FenceController) Queryfence() {
	FileLogs.Info("=====加载电子围栏=====")
	//c.fenceAllowCross()
	token := c.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	FileLogs.Info("公司名：",company)
	page := c.GetString("page")
	size := c.GetString("size")

	departments := models.Getalldepartment(company)
	areas := models.Getallareas(company)

	departmentt := []Department{}
	departsegs := strings.Split(departments, "，")
	for _,item := range departsegs{
		//fmt.Println(item)
		departmentt = append(departmentt,Department{item})
	}

	areaa := []Area{}
	areasegs := strings.Split(areas, "，")
	for _,item := range areasegs{
		areaa = append(areaa,Area{item})
	}

	fenceDataChan := make(chan string, 100000)
	totalItem := models.ReadFence(fenceDataChan,company,page,size)
	fencedata := []Fence{}
	tempdata := Fence{"","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenfencedatachan = len(fenceDataChan)
	if lenfencedatachan != 0 {
		for item := range fenceDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = Fence{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4]}
			fencedata = append(fencedata, tempdata)
			if i == (lenfencedatachan - 1) {
				break
			}
			i++
		}
		data := &FJSONS{0,totalItem,departmentt,areaa,fencedata}
		c.Data["json"] = data
		c.ServeJSON()
	}else {
		fencedata = append(fencedata, tempdata)
		data := &FJSONS{1, totalItem, []Department{},[]Area{},[]Fence{}}
		c.Data["json"] = data
		c.ServeJSON()
	}
}


//根据围栏ID修改围栏信息
func (this *FenceController) ChangeFenceById() {
	FileLogs.Info("===修改电子围栏信息===")
	//this.fenceAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	fmt.Println(company)
	//var obs []CapLabel
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	fmt.Println(string(body))
	fencearray := Getinfofromjson(string(body))
	fmt.Println(fencearray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	//for i := 0; i < len(fencearray); i++ {
		_, err := o.Raw("update fence_info set fencename = ?,department = ? where fenceid = ?",
			fencearray[2], fencearray[4],fencearray[1]).Exec()
		if err != nil {
			fmt.Println("更新失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	//}
	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}


//根据围栏ID删除围栏信息
func (this *FenceController) DeleteFenceById() {
	//this.fenceAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	fmt.Println(company)
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	fmt.Println(string(body))
	fencearray := Getinfofromarray(string(body))
	fmt.Println(fencearray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	for i := 0; i < len(fencearray); i++{
		_, err := o.Raw("delete from  fence_info  where fenceid = ? and company = ?",fencearray[i],company).Exec()
		if err != nil{
			fmt.Println("删除失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}

	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}



//加载某一个围栏坐标
func (this *FenceController) LoadOneFence() {
    FileLogs.Info("===加载某一个围栏坐标===")
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	fenceid:= this.GetString("fenceid")

	fenceDataChan := make(chan string, 100)
	models.ReadOneFence(fenceDataChan,company,fenceid)

	type Fencepoint struct {
		Fenceid string `json:"fenceid"`
		Fencepoint string `json:"fencepoint"`
	}

	type FPJSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
		DATA []Fencepoint  `json:"data"`
	}

	fencedata := []Fencepoint{}
	tempdata := Fencepoint{"",""}
	for item := range fenceDataChan{
		//fmt.Println("get data from database:",item)
		//m[strconv.Itoa(i)] =item
		itemsegments := strings.Split(item,"and")
	    tempdata = Fencepoint{itemsegments[0],itemsegments[1]}
		fencedata = append(fencedata, tempdata)
        break
	}
	data := &FPJSONS{0,fencedata}
	this.Data["json"] = data
	this.ServeJSON()
}




//加载全部围栏坐标
func (c *FenceController) LoadALLFence() {
	//c.fenceAllowCross()
	FileLogs.Info("===加载所有围栏===")
	token := c.Ctx.Request.Header.Get("Authorization")
	//fmt.Println(token)
	company := GetCompanyfromToken(token)
	//fmt.Println(company)
	fenceDataChan := make(chan string, 100)
	models.ReadALLFence(fenceDataChan,company)
	type Fencepoint struct {
		Fencename string `json:"fencename"`
		Fencepoint string `json:"fencepoint"`
	}

	type FPJSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
		DATA []Fencepoint  `json:"data"`
	}

	fencedata := []Fencepoint{}
	tempdata := Fencepoint{"",""}
	var i int = 0
	lenfencedata := len(fenceDataChan)
	for item := range fenceDataChan{
		//fmt.Println("get data from database:",item)
		//m[strconv.Itoa(i)] =item
		itemsegments := strings.Split(item,"and")
		tempdata = Fencepoint{itemsegments[0],itemsegments[1]}
		fencedata = append(fencedata, tempdata)
		if i == (lenfencedata - 1) {
			break
		}
		i++
	}

	data := &FPJSONS{0,fencedata}
	c.Data["json"] = data
	c.ServeJSON()
}


